package Controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.torque.NoRowsException;
import org.apache.torque.TooManyRowsException;
import org.apache.torque.TorqueException;

import Models.Absence;
import Models.AbsencePeer;
import Models.Etudiant;
import Models.EtudiantPeer;
import Models.Module;
import Models.ModulePeer;

@SuppressWarnings("serial")
public class AbsencesController extends MainController {
	private String searchView, addView, errorView;
	// INIT
	public void init() throws ServletException {
		this.searchView	= this.getInitParameter("view_search");
		this.addView 	= this.getInitParameter("view_add");
		this.errorView	= this.getInitParameter("view_error");
	}
	
	// POST
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		String method = request.getMethod().toLowerCase();
		String action = request.getPathInfo();
		if (action == null) {
			action = "/";
			System.out.println("action == null");
		}
		if (method.equals("post") && action.equals("/add")) {
			request.setAttribute("title", "Rechercher un étudiant");
			this.add(request, response);
		} else if (method.equals("post") && action.equals("/search")) {
			request.setAttribute("title", "Rechercher un étudiant");
			this.search(request, response);
		}
	}

	// GET
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		// On récupère la méthode d'envoi de la requête
		String method = request.getMethod().toLowerCase();
		
		// On récupère l'action à exécuter
		String action = request.getPathInfo();
		if (action == null) {
			action = "/";
			System.out.println("action == null");
		}
		
		if (method.equals("get") && action.equals("/add")) {
			this.add(request, response);
		} else if (method.equals("get") && action.equals("/search")) {
			request.setAttribute("title", "Rechercher un étudiant");
			this.search(request, response);
		}
	}

	private void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("etu", new ArrayList<Etudiant>());
		if (request.getParameter("search") != null) {
			ArrayList<Etudiant> etu = EtudiantPeer.doSelectLike(request.getParameter("nom"));
			request.setAttribute("etu", etu);
		}
		this.loadJSP(this.searchView, request, response);
	}
	
	private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Etudiant etu = new Etudiant();
		try {
			etu = EtudiantPeer.retrieveByPK(Integer.parseInt(request.getParameter("e")));
			ArrayList<Module> modules = ModulePeer.doSelectAll();
			request.setAttribute("etu", etu);
			request.setAttribute("title", "Ajouter une absence pour "+etu.getNom());
			request.setAttribute("modules", modules);
			if (request.getParameter("abs") != null) {
				int		mod = Integer.parseInt(request.getParameter("module"));
				Date	date = new Date();
				String	d[] = request.getParameter("date").trim().split(" "),
						motif = request.getParameter("motif").trim();
				boolean err = false;
				if (mod == 0) {
					request.setAttribute("err-mod", "Le module doit être renseigné");
					err = true;
				}
				if (d.length != 2 ||
						d.length == 2 && !d[0].matches("^[0-9]{2}/[0-9]{2}/[0-9]{4}$") ||
						d.length == 2 && !d[1].matches("^[0-9]{2}:[0-9]{2}$")) {
					request.setAttribute("err-date", "La date n'est pas correctement formatée");
					err = true;
				} else {
					String h[] = d[1].split(":");
					d = d[0].split("/");
					if (d.length != 3 || h.length != 2 ||
							d.length == 3 && d[2].length() != 4 && d[1].length() != 2 && d[0].length() != 2 ||
							h.length == 3 && h[1].length() != 2 && h[0].length() != 2) {
						request.setAttribute("err-date", "La date n'est pas correctement formatée");
						err = true;
					} else {
						date = new GregorianCalendar(
								Integer.parseInt(d[2]),
								Integer.parseInt(d[1])-1,
								Integer.parseInt(d[0]),
								Integer.parseInt(h[0]),
								Integer.parseInt(h[1])).getTime();
					}
				}
				if (!err) {
					Absence a = new Absence(etu.getIdEtudiant(), mod, date, motif);
					request.setAttribute("message", "L'absence a bien été enregistrée");
					try {
						// Si la méthode lève une exception c'est qu'aucune absence n'a été faite, donc on insère
						AbsencePeer.retrieveByPK(etu.getIdEtudiant(), mod, date);
						AbsencePeer.doUpdate(a);
					} catch (TorqueException e) {
						AbsencePeer.doInsert(a);
					}
				}
			}
			this.loadJSP(this.addView, request, response);
		} catch (NoRowsException e) {
			request.setAttribute("message", "Cet étudiant n'existe pas");
			request.setAttribute("title", "Erreur");
			request.setAttribute("title_error", "Aucun étudiant");
			this.loadJSP(this.errorView, request, response);
		} catch (TooManyRowsException e) {
			e.printStackTrace();
		} catch (NumberFormatException e) {
			request.setAttribute("message", "Cet étudiant n'existe pas");
			request.setAttribute("title", "Erreur");
			request.setAttribute("title_error", "Aucun étudiant");
			this.loadJSP(this.errorView, request, response);
		} catch (TorqueException e) {
			e.printStackTrace();
		}
	}
}
